package com.iraeta.service.sys.impl;

import com.iraeta.dao.main.sys.UserDao;
import com.iraeta.entity.main.User;
import com.iraeta.entity.main.UserRole;
import com.iraeta.service.sys.UserService;
import com.iraeta.uitl.Util;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    UserDao userDao;

    /*user相关*/
    @Override
    public void addUser(User user) {
        userDao.insert(user);
    }
    @Override
    public void updateUser(User user) {
        userDao.updateByPrimaryKey(user);
    }
    @Override
    public void deleteUser(int id) {
        userDao.deleteByPrimaryKey(id);
    }
    @Override
    public User getUser(int id) {
        return userDao.selectByPrimaryKey(id);
    }
    @Override
    public User getUserByWxuid(String wxuid) {
        return userDao.selectByWxuid(wxuid);
    }

    @Override
    public User getUserByPhone(String phone) {
        return userDao.selectByPhone(phone);
    }

    @Override
    public User getUserByUserName(String userName, String pwd) {
        return userDao.selectUserByUserName(userName, pwd);
    }
    @Override
    public List<User> listUserByName(String name) {
        return userDao.selectUserByName(name);
    }
    @Override
    public List<User> listOrgUserByName(Integer orgId, String name) {
        return userDao.listOrgUserByName(orgId, name);
    }

    @Override
    public List<User> listUserByPermissionId(Integer permissionId) {
        return userDao.selectUserByPermissionId(permissionId);
    }

    /*user role相关  user set role*/
    @Transactional
    @Override
    public void saveUserRole(int userId, List<Integer> roleList) {
        for (Integer roleId : roleList) {
            if(userDao.selectByUserRole(userId, roleId) == null){
                UserRole userRole = new UserRole(userId, roleId);
                userDao.insertUserRole(userRole);
            }
        }
        String userRoleIdStr = Util.parseListToString(roleList);
        userDao.deleteUserRoleIdStr(userId, userRoleIdStr);
    }

    /*user role相关  role set user*/
    public List<User> listUserByRoleId(int roleId){
        return userDao.selectUserByRoleId(roleId);
    }

    /*user permission相关*/
    @Override
    public List<Integer> listUserPermissions(int userId) {
        return userDao.selectUserPermissions(userId);
    }
}
